package com.version1_3.service.implement;

import com.version1_3.service.CoinService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.EnumMap;
import java.util.Map;

/**
 * Created by kuibu on 16/3/6.
 */
@Service
public class CoinServiceImpl implements CoinService {
    private static final Logger LOGGER = Logger.getLogger(CoinServiceImpl.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 记录用户每日登陆
     *
     * @param userId
     * @return
     */
    @Override
    public boolean recordUserLogin(int userId) {
        String sql = "SELECT id,date,continuousSignDays FROM coin_signRecord WHERE userId=?";

        try {
            Map<String, Object> signRecordMap = jdbcTemplate.queryForMap(sql, new Object[]{userId});
            Date date = (Date) signRecordMap.get("date");

            long time = Calendar.getInstance().getTime().getTime() - date.getTime();
            boolean hasSigned = false;

            // 今日登陆已记录,直接返回true
            if (time >= 0 && time <= 86400000) {
                return true;
            } else {
                recordUserDailyLogin(userId); // 记录用户登陆
            }

            // 今日登陆未记录
            if (time > 86400000 && time <= 86400000 * 2) {
                hasSigned = true;
            }

            // 记录用户登陆积分
            sql = "UPDATE user_info SET userCoin=userCoin+10 WHERE userId=?";
            jdbcTemplate.update(sql, new Object[]{userId});

            if (hasSigned) {
                sql = "UPDATE coin_signRecord SET date=?,continuousSignDays=? WHERE id=?";
                jdbcTemplate.update(sql, new Object[]{new Date(), (int) signRecordMap.get("continuousSignDays") + 1, (long) signRecordMap.get("id")});
            } else {
                sql = "UPDATE coin_signRecord SET date=?,continuousSignDays=1 WHERE id=?";
                jdbcTemplate.update(sql, new Object[]{new Date(), (long) signRecordMap.get("id")});
            }

        } catch (Exception exception) {
            //LOGGER.error("查找当日用户是否登陆未找到相关记录,用户未登陆,userId: " + userId, exception);
            sql = "INSERT INTO coin_signRecord(userId,date) VALUES (?,?)";
            int row = jdbcTemplate.update(sql, new Object[]{userId, new Date()});

            // 记录用户登陆积分
            sql = "UPDATE user_info SET userCoin=userCoin+10 WHERE userId=?";
            jdbcTemplate.update(sql, new Object[]{userId});

            recordUserDailyLogin(userId); // 记录用户登陆

            if (row != 1) return false; // 插入记录失败
        }
        return true;
    }

    /**
     * 模块记录
     *
     * @param userId
     * @param moduelName
     * @param moduleAction
     * @param firstCoin
     * @param addupCoin
     * @param topCoin
     * @return
     */
    @Override
    public boolean moduleRecord(int userId, String moduelName, String moduleAction, int firstCoin, int addupCoin, int topCoin) {
        String sql = "SELECT id,coin FROM coin_moduleRecord WHERE userId=? AND module=? AND action=? AND date=CURRENT_DATE";

        try {
            Map<String, Object> moduleRecordMap = jdbcTemplate.queryForMap(sql, new Object[]{userId, moduelName, moduleAction});
            if ((int) moduleRecordMap.get("coin") + addupCoin <= topCoin) {
                sql = "UPDATE coin_moduleRecord SET coin=coin+? WHERE id=?";
                int row = jdbcTemplate.update(sql, new Object[]{addupCoin, (long) moduleRecordMap.get("id")});

                if (row != 1) {
                    LOGGER.error("用户模块动作添加积分失败,moduleName: " + moduelName + " ,moduleAction: " + moduleAction + " ,userId: " + userId);
                    return false;
                }
            }

        } catch (EmptyResultDataAccessException exception) {
            LOGGER.info("模块记录查找失败,用户改模块的动作今天未进行,moduleName: " + moduelName + " ,moduleAction: " + moduleAction);
            sql = "INSERT INTO coin_moduleRecord(userId,module,date,action,coin) VALUES (?,?,?,?,?)";
            int row = jdbcTemplate.update(sql, new Object[]{userId, moduelName, new Date(), moduleAction, firstCoin});

            if (row != 1) {
                LOGGER.error("模块记录当日第一次插入记录失败,moduleName: " + moduelName + " ,moduleAction: " + moduleAction + " ,userId: " + userId);
            }
        }
        return false;
    }


    /**
     * 记录用户分享App
     *
     * @param userId
     * @return
     */
    @Override
    public boolean recordUserShareApp(int userId) {
        String sql = "SELECT userShareAppCoin FROM user_info WHERE userId=?";

        try {
            int userShareAppCoin = jdbcTemplate.queryForObject(sql, new Object[]{userId}, java.lang.Integer.class);

            // 如果用户累计分享积分不超过500则继续增加
            if (userShareAppCoin + 50 <= 500) {
                sql = "UPDATE user_info SET userShareAppCoin=userShareAppCoin+50 WHERE userId=?";
                int rows = jdbcTemplate.update(sql, new Object[]{userId});

                return (rows == 1) ? true : false;
            } else {
                return true;
            }
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("记录用户分享App获得积分错误,根据userId找不到用户,userId: " + userId);
            return false;
        }
    }

    /**
     * 记录用户完善个人信息积分
     *
     * @param userId
     * @return
     */
    @Override
    public boolean recordUserCompleteInfoCoin(int userId) {
        String sql = "SELECT userCompleteInfoCoin FROM user_info WHERE userId=?";

        try {
            int userCompleteInfoCoin = jdbcTemplate.queryForObject(sql, new Object[]{userId}, java.lang.Integer.class);
            if (userCompleteInfoCoin != 100) {
                sql = "UPDATE user_info SET userCompleteInfoCoin=100 WHERE userId=?";
                int rows = jdbcTemplate.update(sql, new Object[]{userId});

                return (rows == 1) ? true : false;
            }

            return false;
        } catch (EmptyResultDataAccessException exception) {
            LOGGER.error("根据userId获取用户信息错误,userId: " + userId);
            return false;
        }
    }


    public boolean recordUserDailyLogin(int userId) {
        String sql = "INSERT INTO user_dailyLoginRecord(userId,loginTime) VALUES (?,?)";
        try {
            jdbcTemplate.update(sql, new Object[]{userId, new Timestamp(new Date().getTime())});
        } catch (Exception exception) {
            LOGGER.error("记录用户登陆失败", exception);
            return false;
        }
        return true;
    }
}
